<template>
  <!-- 面包屑导航 -->
  <div>
    <!-- <el-breadcrumb separator="/" class="nav">
      <el-breadcrumb-item>
        <a href="/">首页</a>
      </el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>-->
    <my-bread level1="用户管理" level2="用户列表"></my-bread>

    <!-- 搜索框 -->
    <el-col :span="6">
      <el-input
        placeholder="请输入搜索内容"
        class="input-with-select"
        v-model="query"
        @input="isNull()"
        clearable
      >
        <el-button slot="append" icon="el-icon-search" @click="searchUser()"></el-button>
      </el-input>
    </el-col>
    <!-- 添加用户 -->
    <el-button type="success" class="btnAdd" @click="addUser">添加用户</el-button>

    <!-- 表格 -->
    <el-table :data="usersList" style="width: 100%">
      <el-table-column type="index" label="#编号" width="180"></el-table-column>
      <el-table-column prop="username" label="姓名" width="180"></el-table-column>
      <el-table-column prop="email" label="邮箱"></el-table-column>
      <el-table-column prop="mobile" label="电话" width="180"></el-table-column>
      <el-table-column prop="create_time" label="创建日期" width="180"></el-table-column>
      <el-table-column prop="mg_state" label="用户状态">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.mg_state"
            active-color="#13ce66"
            inactive-color="#ff4949"
            @change="setUserState(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column prop="address" label="操作">
        <template slot-scope="scope">
          <el-button
            type="primary"
            icon="el-icon-edit"
            size="mini"
            plain
            circle
            @click="editUserBtn(scope.row)"
            title="编辑"
          ></el-button>
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            plain
            circle
            title="删除"
            @click="deleteUser(scope.row.id)"
          ></el-button>
          <el-button
            type="success"
            icon="el-icon-check"
            size="mini"
            plain
            circle
            title="用户权限"
            @click="userLimit(scope.row)"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-col :span="12" :offset="12" class="page">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :page-sizes="[4, 8, 12, 24, 36]"
        :page-size="4"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-col>

    <!-- 添加用户 -->
    <el-dialog title="添加用户" :visible.sync="dialogFormVisible">
      <el-form label-width="80px">
        <el-form-item label="姓名: ">
          <el-input v-model="addUsersList.username"></el-input>
        </el-form-item>
        <el-form-item label="密码: ">
          <el-input v-model="addUsersList.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱: ">
          <el-input v-model="addUsersList.email"></el-input>
        </el-form-item>
        <el-form-item label="电话: ">
          <el-input v-model="addUsersList.mobile"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addUserBtnOff()">取 消</el-button>
        <el-button type="primary" @click="addUserBtn()">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 编辑用户 -->
    <el-dialog title="编辑用户" :visible.sync="dialogFormVisibleEdit">
      <el-form label-width="80px">
        <el-form-item label="用户名: ">
          <el-input v-model="editUsersInfo.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱: ">
          <el-input v-model="editUsersInfo.email"></el-input>
        </el-form-item>
        <el-form-item label="电话: ">
          <el-input v-model="editUsersInfo.mobile"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editUserOff()">取 消</el-button>
        <el-button type="primary" @click="editUserBtnOk()">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 分配角色  用户权限-->
    <el-dialog title="分配用户权限" :visible.sync="dialogFormVisibleLimit">
      <el-form>
        <el-form-item label="用户名: ">
          <!-- <el-input autocomplete="off"></el-input> -->
          {{currentUserName}}
        </el-form-item>
        <!-- {{this.currentrolesId}} -->
        <el-form-item label="角色:">
          <el-select v-model="currentrolesId">
            <el-option label="请选择" :value="-1" disabled></el-option>
            <el-option v-for="(v,i) in rolesList" :key="i" :label="v.roleName" :value="v.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="userLimitOff()">取 消</el-button>
        <el-button type="primary" @click="userLimitBtn()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      //   获取用户数据
      query: '',
      //   当前页码
      pagenum: 1,
      //   每页显示条数
      pagesize: 4,
      // 总条数
      total: -1,

      usersList: [{
        username: '',
        email: '',
        mobile: '',
        create_time: '',
        mg_state: ''
      }],
      // 添加用户弹出框控制
      dialogFormVisible: false,
      dialogTableVisible: false,
      addUsersList: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 编辑用户弹出框状态
      dialogFormVisibleEdit: false,
      // 编辑用户信息
      editUsersInfo: {
        username: '',
        email: '',
        mobile: ''
      },
      // 分配用户权限弹出框
      dialogFormVisibleLimit: false,
      // 角色列表
      rolesList: [],
      // 当前用户角色ID
      currentrolesId: -1,
      // 当前用户用户名
      currentUserName: '',
      // 当前用户的ID
      currentUserId: ''

    }
  },
  created () {
    this.getAllUsers()
  },
  methods: {
    // 获取所有用户数据
    async getAllUsers () {

      const res = await this.$http(`users?query=${this.query}&pagenum=${this.pagenum}&pagesize=${this.pagesize}`)
      //   console.log(this)
      // console.log(res)
      // 结构赋值
      const { meta: { mag, status }, data } = res.data
      this.usersList = data.users
      this.total = data.total
      //   console.log(this.total)
    },
    // 分页
    handleSizeChange (val) {
      // console.log(`每页 ${val} 条`)
      this.pagesize = val
      this.getAllUsers()
    },
    handleCurrentChange (val) {
      // console.log(`当前页: ${val}`)
      this.pagenum = val
      this.getAllUsers()
    },
    // 添加用户
    addUser () {
      this.dialogFormVisible = true
    },
    async addUserBtn () {
      this.dialogFormVisible = false
      const res = await this.$http.post('users', this.addUsersList)
      // console.log(res)
      console.log(this.addUsersList)
      const { meta: { msg, status } } = res.data
      if (status === 201) {
        this.$message.success(msg)
      } else {
        this.$message.warning(msg)
      }
      //   清空输入框
      this.addUsersList = {}

      // 更新视图
      this.getAllUsers()
    },
    // 添加用户按钮关闭
    addUserBtnOff () {
      // 关闭弹框
      this.dialogFormVisible = false
      //   清空输入框
      this.addUsersList = {}
    },
    // 用户搜索
    searchUser () {
      //   alert(1)
      this.pagenum = 1
      //   更新视图
      this.getAllUsers()
    },

    isNull () {
      // 判断 搜索输入框 query 的值 是否为空
      if (this.query.length == 0) {
        this.getAllUsers()
        // alert(1)
      }
    },
    // 编辑用户
    editUserBtn (user) {
      //   alert(1)
      this.editUsersInfo = user
      this.dialogFormVisibleEdit = true
      // console.log(user)
    },
    editUserOff () {
      // this.editUsersInfo={}
      // alert(1)
      this.dialogFormVisibleEdit = false
      this.getAllUsers()
    },
    async editUserBtnOk () {
      this.dialogFormVisibleEdit = false
      // alert(1)
      //  用户id this.editUsersInfo.id   因为 user赋值给了this.editUsersInfo  所以this.editUsersInfo 存了user的所有信息
      const res = await this.$http.put(`users/${this.editUsersInfo.id}`, this.editUsersInfo)
      // console.log(res)
      // 解构赋值
      const { meta: { msg, status } } = res.data
      if (status === 200) {
        this.$message.success(msg)
        this.getAllUsers()
      } else {
        this.$message.error(msg)
      }
    },
    // 删除用户
    deleteUser (ID) {
      this.$confirm('是否删除该用户?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const res = await this.$http.delete(`users/${ID}`)
        const { meta: { msg, status } } = res.data
        if (status === 200) {
          this.$message({
            type: 'success',
            message: msg
          })
          // 更新视图
          this.getAllUsers()
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        })
      })
    },
    // 用户权限
    async userLimit (user) {
      this.dialogFormVisibleLimit = true
      // 获取所有角色
      const res = await this.$http.get('roles')
      // console.log(res)
      this.rolesList = res.data.data
      // console.log(this.rolesList)

      const res1 = await this.$http.get(`users/${user.id}`)
      // console.log(res1)
      this.currentrolesId = res1.data.data.rid
      this.currentUserName = res1.data.data.username
      this.currentUserId = res1.data.data.id
      // this.currentUserId =
      // console.log(this.currentUserId)
    },
    userLimitOff () {
      this.dialogFormVisibleLimit = false
    },
    async userLimitBtn () {
      const res = await this.$http.put(`users/${this.currentUserId}/role`, { rid: this.currentrolesId })
      // 解构
      const { meta: { msg, status } } = res.data
      if (status == 200) {
        this.$message.success(msg)
      }
      this.dialogFormVisibleLimit = false
    },
    // 设置用户状态
    async setUserState (user) {
      // alert(1)
      // console.log(user)
      const res = await this.$http.put(`users/${user.id}/state/${user.mg_state}`)
      // console.log(res)
      const { meta: { msg, status }, data: { mg_state } } = res.data
      // console.log(mg_state)
      if (status === 200 && mg_state === 1) return this.$message.success('该用户已启用')
      if (status === 200 && mg_state === 0) return this.$message.success('该用户已禁用')
    }

  }
}

</script>

<style>

.btnAdd {
  margin-left: 10px;
}
.page {
  margin-top: 20px;
}
</style>
